//
//  ImagePicer.swift
//  IdleFish
//
//  Created by Ben on 2021/12/20.
//

import SwiftUI

typealias ImagePickerImageIsSelected = (UIImage) -> ()

struct ImagePicer: UIViewControllerRepresentable {
    
    @Environment(\.presentationMode) private var preseatationModel
    
    let sourceType: UIImagePickerController.SourceType
    let imageIsSelected: ImagePickerImageIsSelected
    
    func makeCoordinator() -> Coordinator {
        return Coordinator(presentationModel: preseatationModel, imageIsSelected: imageIsSelected)
    }
    
    func makeUIViewController(context: Context) -> UIImagePickerController {
        let imagePickerVC = UIImagePickerController()
        imagePickerVC.delegate = context.coordinator
        // 更正在上个视频的一个小错误，这里需要把sourceType赋值给imagePickerVC.sourceType，否则无法调起摄像头拍摄，之前粗心忘记设置了，请见谅
        imagePickerVC.sourceType = sourceType
        return imagePickerVC
    }
    
    func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {
        
    }
    
    typealias UIViewControllerType = UIImagePickerController
    
    
    class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
        
        @Binding private var presentationModel: PresentationMode
        
        private let imageIsSelected: ImagePickerImageIsSelected
        
        init(presentationModel: Binding<PresentationMode>, imageIsSelected: @escaping (UIImage) -> Void) {
            _presentationModel = presentationModel

            self.imageIsSelected = imageIsSelected
        }
        
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            let image = info[.originalImage] as! UIImage
            imageIsSelected(image)
            presentationModel.dismiss()
        }
        
        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            presentationModel.dismiss()
        }
        

    }
    
}
